<template>
  <div class="app-container">
    <el-container style="height: 760px; border: 1px solid #eee">
      <el-aside style="width: 460px;background-color: #ffffff">
        <div class="container" style="width: 100%;">
          <el-divider content-position="center">{{ editTitle }}</el-divider>
          <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" label-width="110px" style="padding-left: 10px; padding-top: 15px;">
            <el-form-item label="上级配置" size="mini" prop="pid" >
              <el-select v-model="addData.pid" placeholder="请选择" :disabled="addData.id > 0" @change="handleParentChange" style="width: 190px;">
                <el-option
                  v-for="item in parentOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="配置标识" size="mini" prop="sign" style="width: 300px;">
              <el-input v-model="addData.sign" />
            </el-form-item>
            <el-form-item label="配置标题" size="mini" prop="title" style="width: 300px;">
              <el-input v-model="addData.title" />
            </el-form-item>
            <el-form-item label="配置类型" size="mini" prop="pid" >
              <el-radio-group v-model="addData.configure_type" size="mini">
                <el-radio-button v-for="(item, i) in configureTypeOption" :key="i" :label="item.type">{{item.title}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="addData.pid !== 0" label="配置数据" size="mini" prop="value" style="width: 300px;">
              <el-input v-model="addData.value"/>
            </el-form-item>
            <el-form-item label="配置描述" size="mini" prop="path" style="width: 300px;">
              <el-input v-model="addData.mark" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button style="float: right; margin-right: 100px;" size="mini" type="primary" @click="handleAddSubmit()">提交</el-button>
            <el-button style="float: right; margin-right: 12px;" size="mini" v-waves type="primary" @click="resetQueryForm('addForm')">重置</el-button>
          </div>
        </div>
      </el-aside>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="list"
          size="mini"
          row-key="Id"
          highlight-current-row
          style="width: 100%"
          :tree-props="{children: 'Children', hasChildren: true}"
        >
          <el-table-column align="left" label="ID" width="160">
            <template slot-scope="{row}">
              <span>{{ row.Id }}</span>
            </template>
          </el-table-column>
          <el-table-column width="200px" align="left" label="标题">
            <template slot-scope="{row}">
              <span>{{ row.Title }}</span>
            </template>
          </el-table-column>

          <el-table-column width="120px" align="left" label="标识">
            <template slot-scope="{row}">
              <span>{{ row.Sign }}</span>
            </template>
          </el-table-column>
          <el-table-column width="160px" align="left" label="值">
            <template slot-scope="{row}">
              <span>{{ row.Value }}</span>
            </template>
          </el-table-column>
          <el-table-column width="50px" align="left" label="排序">
            <template slot-scope="{row}">
              <span>{{ row.Sort }}</span>
            </template>
          </el-table-column>

          <el-table-column class-name="status-col" align="left" label="状态" width="120">
            <template slot-scope="{row}">
              <i class="el-icon-check" style="color: green" v-if="row.Status"></i>
              <i class="el-icon-close" style="color: red" v-if="!row.Status"></i>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作">
            <template slot-scope="{row}">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleEdit(row.Id)"
              >
              </el-button>
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="handleDel(row.Id)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { systemConfigureList, systemConfigureAdd, systemConfigureDetail, systemConfigureDel } from '@/api/system'
import waves from '@/directive/waves'
import { strLength } from '@/utils/common'

export default {
  name: 'PartnerConfigureList',
  components: { },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '禁用',
        '1': '启用'
      }
      return statusMap[status]
    }
  },
  data() {
    const checkTitle = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 名称不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 24 || strLen < 6) {
        return callback(new Error('对不起， 用户名长度为6-24个字符,汉字为3个字符!'))
      }

      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 用户名只能包含汉字,数字,字母'))
      } else {
        callback()
      }
    }
    const checkSign = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 配置标识不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 24 || strLen < 4) {
        return callback(new Error('对不起， 配置标识为4-24个字符!'))
      }

      const reg = /^[A-Za-z0-9_]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 用户名只能包含数字,字母,下划线'))
      } else {
        callback()
      }
    }
    const checkValue = function(rule, value, callback) {
      if (this.addData.pid === 0) {
        return callback()
      }

      if (!value) {
        return callback(new Error('对不起， 非顶级配置，值不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 64 || strLen < 1) {
        return callback(new Error('对不起， 配置长度为1-64个字符!'))
      }

      const reg = /^[_A-Za-z0-9,:|\-\/]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 配置只能包含数字,字母,下划线,反斜线,中横线,逗号，冒号，竖线'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      listLoading: true,
      listQuery: {
        page_index: 1,
        page_size: 10
      },
      editTitle: '添加菜单',
      parentOption: [],
      configureTypeOption: [],
      addData: {
        pid: 0,
        id: '0',
        title: '',
        configure_type: 'string',
        sign: '',
        value: '',
        sort: '',
        mark: ''
      },
      rules: {
        id: [],
        pid: [{ required: true, message: '需要选择上级配置', trigger: 'blur' }],
        title: [
          { required: true, message: '需要填写配置标题', trigger: 'blur' },
          { validator: checkTitle.bind(this), message: '需要填写配置标题', trigger: 'blur' }
        ],
        value: [
          { validator: checkValue.bind(this), message: '需要填写配置数据', trigger: 'blur' }
        ],
        sign: [
          { required: true, message: '需要填写标识', trigger: 'blur' },
          { validator: checkSign, trigger: 'blur' }
        ],
        mark: [
          { required: true, message: '需要填写前端对应路径', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.editTitle = '添加配置'
  },
  methods: {
    resetAddData() {
      this.addData = {
        pid: 0,
        id: '0',
        title: '',
        configure_type: 'string',
        sign: '',
        value: '',
        sort: '',
        mark: ''
      }
    },
    getList() {
      this.listLoading = true
      systemConfigureList(this.listQuery).then(response => {
        if (response.success) {
          this.list = response.data.data
          this.parentOption = response.data.parent_option
          this.configureTypeOption = response.data.configure_type_option
          this.listLoading = false
        } else {
          this.$message({
            type: 'error',
            message: '获取数据列表失败!'
          })
        }
      })
    },
    handleEdit(id) {
      this.resetAddData()
      if (+id > 0) {
        systemConfigureDetail(id).then((response) => {
          if (response.success) {
            this.addData = response.data
            this.addData.pid = +this.addData.pid
          }
        })
        this.editTitle = '编辑配置-' + id
      }
      this.$nextTick(() => {
        this.$refs['addForm'].clearValidate()
      })
    },
    handleAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          systemConfigureAdd(this.addData).then((response) => {
            if (response.success) {
              this.$message({
                type: 'success',
                message: response.msg
              })
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleParentChange(pid) {
      if (pid > 0) {
        this.addData.level = 2
      } else {
        this.addData.level = 1
      }
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除选择配置数据,并删除子配置单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        systemConfigureDel(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetQueryForm(formName) {
      this.$refs[formName].resetFields()
      this.editTitle = '添加配置'
      this.resetAddData()
    }
  }
}
</script>
